package com.service.impl;


import com.dao.*;
import com.exception.ServiceRuntimeException;
import com.model.PhoneNumVerifyCode;
import com.model.SysUser;
import com.result.Result;
import com.service.LoginService;
import com.utils.AliMessageSender;
import com.vo.LoginData;
import com.vo.PermissionRoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service("loginService")
public class LoginServiceImpl implements LoginService {


    @Autowired
    private SysUserMapper  sysUserMapper;

    @Autowired
    private PermissionSysUserRoleMapper permissionSysUserRoleMapper;

    @Autowired
    private PermissionRoleResourceMapper permissionRoleResourceMapper;

    @Autowired
    private PermissionResourceMapper permissionResourceMapper;

    @Autowired
    private PhoneNumVerifyCodeMapper phoneNumVerifyCodeMapper;

    @Autowired
    private AliMessageSender aliMessageSender;


    @Override
    public Result<LoginData> backLogin(String username, String password, HttpServletRequest request, HttpServletResponse response) {
         Result<LoginData>  result=new Result<>();
        LoginData  loginData=new LoginData();
        if (StringUtils.isEmpty(username)){
            return new Result<>().error("用户名为空");
        }
        if (StringUtils.isEmpty(password)){
            return new Result<>().error("用户名为空");
        }
        SysUser user = sysUserMapper.selectByUserName(username.trim());
        if(ObjectUtils.isEmpty(user)){
            return new Result<>().error("用户不存在");
        }
        if (user.getStatus()!=1){
            return new Result<>().error("账号状态异常");
        }
        if (!password.equals(user.getPassword())) {
            return new Result<>().error("用户名或密码错误");
        }

        List<PermissionRoleVO> roleVOList = permissionSysUserRoleMapper.selectRoleListByUserId(user.getId());
        loginData.setUserId(user.getId());
        loginData.setUserType(user.getUserType());
        loginData.setRoleList(roleVOList);
        loginData.setUsername(user.getUserName());
        loginData.setHeadImgUrl(user.getAvatar());
        loginData.setLeaderId(user.getLeaderId());
        //把用户信息保存在session中
        HttpSession session = request.getSession(true);
        session.setAttribute(String.valueOf(user.getId()), loginData);
        session.setAttribute("curUser", loginData);
        //以秒为单位
        //设置时间为12小时
        session.setMaxInactiveInterval(24 * 60 * 60);
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(session.getMaxInactiveInterval());
        cookie.setPath(request.getServletContext().getContextPath());
        cookie.setHttpOnly(true);
        cookie.setDomain("www.houluzhai.top");
        cookie.setPath("/");
        response.addCookie(cookie);
        return result.ok(loginData);
    }

    @Override
    public Result<Boolean> getVerifyCode(String phoneNum, HttpServletRequest request, HttpServletResponse response) {
        Result<Boolean> result = new Result<>();
        //生成短信验证码
        String random = (int) ((Math.random() * 9 + 1) * 1000) + "";
        Boolean issend = aliMessageSender.sendVerCode(phoneNum, random);
        if(issend){
            //短信验证码入库
            PhoneNumVerifyCode verifyCode=new PhoneNumVerifyCode();
            verifyCode.setPhoneNum(phoneNum);
            verifyCode.setVerifyCode(random);
            verifyCode.setValidTime(System.currentTimeMillis());
            verifyCode.setCreated(null);
            verifyCode.setCreateTime(new Date());
            phoneNumVerifyCodeMapper.insert(verifyCode);
            return result.ok(true);
        }
        return result.ok(false);
    }

    @Override
    public Result<Boolean> resetPassword(String phoneNum, String verifyCode, String newPassword, HttpServletRequest request, HttpServletResponse response) {
        Assert.notNull(verifyCode,"短信验证码不能为空");
        Result<Boolean> result = new Result<>();
        Date  now=new Date();
        SysUser  sysUser= sysUserMapper.selectByMobile(phoneNum);
        if(ObjectUtils.isEmpty(sysUser)){
            return  result.error("此手机号尚未和系统账号绑定");
        }
        //校验验证码上是否正确
        PhoneNumVerifyCode phoneNumVerifyCode= phoneNumVerifyCodeMapper.selectByPhoneNumAndVerifyCode(phoneNum,verifyCode);
        if(ObjectUtils.isEmpty(phoneNumVerifyCode)){
            return  result.error("验证码错误");
        }
        Long minute= ((now.getTime()-phoneNumVerifyCode.getValidTime())/1000/60);
        if(minute>5){
            return  result.error("验证码已过期");
        }
        sysUser.setPassword(newPassword.trim());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        CompletableFuture  completableFuture=CompletableFuture.runAsync(()->{
            //把该手机号相关的历史记录全删除
            phoneNumVerifyCodeMapper.deleteByPhoneNum(phoneNum);
        });
        return result.ok(true);
    }
}
